package com.quan.system.web.controller;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.common.annotation.Log;
import com.quan.common.bean.PageBean;
import com.quan.common.bean.R;
import com.quan.common.core.MyBaseController;
import com.quan.common.enums.DateStyle;
import com.quan.common.enums.LogType;
import com.quan.common.properties.SystemValueProperties;
import com.quan.common.utils.DateUtils;
import com.quan.common.utils.FileUtils;
import com.quan.common.utils.RandomUitl;
import com.quan.system.entity.SystemFile;
import com.quan.system.service.SystemFileService;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 图片表 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2020-03-05
 */
@Api(tags ="文件上传")
@RestController
@RequestMapping("/system/file")
public class SystemFileController extends MyBaseController {

	@Autowired 
    private SystemFileService service;
	
	@Autowired 
	private SystemValueProperties properties;
    
    /**
	 * 添加
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/add") @Log(type=LogType.BUSINESS, desc = "添加")
	public Object add(@Valid @RequestBody SystemFile entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return R.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}
		boolean save = this.service.save(entity);
		if (save) {
			return R.ok("提交成功");
		} else {
			return R.failure("提交失败");
		}
	}

	/**
	 * 根据ID删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/deleteById/{id}") @Log(type=LogType.BUSINESS, desc = "根据ID删除")
	public Object deleteById(@PathVariable String id) {
		if (StringUtils.isNotBlank(id)) {
			boolean remove = this.service.removeById(id);
			if (remove) {
				return R.ok();
			} else {
				return R.failure("通过ID删除失败：[ " + id + " ]");
			}
		}
		return R.failure("请选项需要删除的记录");
	}

	/**
	 * 根据ID批量删除
	 * 
	 * @param idList ["1","2"]
	 * @return
	 */
	@PostMapping("/deleteBatchIds") @Log(type=LogType.BUSINESS, desc = "根据ID批量删除")
	public Object deleteBatchIds(@RequestBody Map<String, Object> params) {
		if (null != params && !params.isEmpty()) {
			List<Long> idList = JSON.parseArray(params.get("idList").toString(), Long.class);
			boolean remove = this.service.removeByIds(idList);
			if (remove) {
				return R.ok();
			} else {
				return R.failure("通过ID删除失败：[ " + idList + " ]");
			}
		}
		return R.failure("请选项需要删除的记录");
	}
	
	@PostMapping("/deleteByUrl") @Log(type=LogType.BUSINESS, desc = "根据URL批量删除")
	public Object deleteByUrl(@RequestBody Map<String, Object> params) {
		if (null != params && !params.isEmpty()) {
			if(null != params.get("url")) {
				String url = params.get("url").toString();
				
				QueryWrapper<SystemFile> queryWrapper = new QueryWrapper<SystemFile>();
				queryWrapper.eq("url", url);
				SystemFile file = this.service.getOne(queryWrapper);
				
				String path = this.properties.getUpload() + File.separator ;
				FileUtil.del(path + file.getPath()) ;
				this.service.removeById(file.getId());
				
				return R.ok();
			}
		}
		return R.failure("请选项需要删除的记录");
	}

	/**
	 * 修改
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/update") @Log(type=LogType.BUSINESS, desc = "修改")
	public Object update(@Valid @RequestBody SystemFile entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return R.failure(bindingResult.getFieldError().getDefaultMessage().toString());
		}
		boolean update = this.service.updateById(entity);
		if (update) {
			return R.ok("修改成功");
		} else {
			return R.failure("修改失败");
		}
	}

	/**
	 * 根据ID查询
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/get/{id}") @Log(type=LogType.BUSINESS, desc = "根据ID查询")
	public Object get(@PathVariable Long id) {
		SystemFile entity = this.service.getById(id);
		if (null != entity) {
			return R.ok(entity);
		} else {
			return R.failure("通过ID查询失败：[ " + id + " ]");
		}
	}

	/**
	 * 查询所有数据，不分页
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/list") @Log(type=LogType.BUSINESS, desc = "查询所有数据")
	public Object list(SystemFile entity) {
		return R.ok(this.service.list(new QueryWrapper<SystemFile>(entity).orderByDesc("ctime")));
	}

	/**
	 * 分页查询数据
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/page") @Log(type=LogType.BUSINESS, desc = "分页查询数据")
	public Object page(SystemFile entity) {
		return R.ok(this.service.selectPage(entity, new PageBean(request)));
	}
	
	/**
	 * 自定义分页查询数据
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/selectMyPage") @Log(type=LogType.BUSINESS, desc = "自定义分页查询数据")
	public Object selectMyPage(SystemFile entity) {
		return R.ok(this.service.selectMyPage(entity, new PageBean(request)));
	}
	
	/**
	 * 上传图片
	 * @param request
	 * @param destDir 目标目录
	 * @return
	 */
	@ApiOperation(value="上传文件")
	@PostMapping(value = "/upload")
	public Object upload(HttpServletRequest request, String destDir) {
		try {
			String path = this.properties.getUpload() + File.separator ;
			String folder = (StringUtils.isNotBlank(destDir)?destDir + File.separator: "") + DateUtils.getDate(DateStyle.YYYYMMDD.getValue()) + File.separator;
			FileUtils.createDir(path + folder) ;
			
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

			// 取得MultiValueMap集合
			MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
			Set<Entry<String, List<MultipartFile>>> entrySet = multiFileMap.entrySet();
			for (Entry<String, List<MultipartFile>> entry : entrySet) {

				// 获取MultipartFile集合
				List<MultipartFile> multipartFiles = entry.getValue();
				for (MultipartFile multipartFile : multipartFiles) {
					String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
					String filename = DateUtils.format(new Date(), DateStyle.YYYYMMDDHHMMSSS) + "_" + RandomUitl.generateInteger(4) + "." + extension ;
					String dest = path + folder + filename ;
					
					logger.info("==>文件上传：{}==={}", dest, FileUtil.readableFileSize(multipartFile.getSize()));
					
					multipartFile.transferTo(new File(dest));
					
					String url = this.properties.getUploadUrl() + folder + filename ;
					
					SystemFile entity = new SystemFile();
					entity.setName(filename);
					entity.setSize(multipartFile.getSize());
					entity.setType(multipartFile.getContentType());
					entity.setPath(folder + filename);
					entity.setUrl(url.replaceAll("\\\\", "/")) ;
					this.service.save(entity);
					
					return R.ok("文件上传成功", entity);
				}
			}
		} catch (Exception e) {
			return R.errorMsg("文件上传失败", e.getMessage()) ;
		}
		return R.ok();
	}

}






